import java.util.*;
import java.text.SimpleDateFormat;

public class CinemaManagementSystem {
    public static void main(String[] args) {
        SystemInitializer.initialize();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("=== 影院管理系统 ===");
            System.out.println("1. 登录");
            System.out.println("2. 退出系统");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    login(scanner);
                    break;
                case 2:
                    System.out.println("感谢使用影院管理系统，再见！");
                    System.exit(0);
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void login(Scanner scanner) {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();

        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        User user = UserService.authenticate(username, password);

        if (user == null) {
            System.out.println("用户名或密码错误！");
            return;
        }

        switch (user.getUserType()) {
            case ADMIN:
                AdminMenu.showMenu(user, scanner);
                break;
            case MANAGER:
                ManagerMenu.showMenu(user, scanner);
                break;
            case FRONT_DESK:
                FrontDeskMenu.showMenu(user, scanner);
                break;
        }
    }
}

class User {
    private String userId;
    private String username;
    private String password;
    private Date registerTime;
    private UserType userType;
    private String phone;
    private boolean passwordChanged;

    public enum UserType {
        ADMIN, MANAGER, FRONT_DESK
    }//

    public User(String userId, String username, String password, Date registerTime,
                UserType userType, String phone) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.registerTime = registerTime;
        this.userType = userType;
        this.phone = phone;
        this.passwordChanged = false;
    }

    public String getUserId() { return userId; }
    public String getUsername() { return username; }
    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }
    public Date getRegisterTime() { return registerTime; }
    public UserType getUserType() { return userType; }
    public void setUserType(UserType userType) { this.userType = userType; }
    public String getPhone() { return phone; }
    public void setPhone(String phone) { this.phone = phone; }
    public boolean isPasswordChanged() { return passwordChanged; }
    public void setPasswordChanged(boolean passwordChanged) { this.passwordChanged = passwordChanged; }

    @Override
    public String toString() {
        return "User{" +
                "userId='" + userId + '\'' +
                ", username='" + username + '\'' +
                ", registerTime=" + registerTime +
                ", userType=" + userType +
                ", phone='" + phone + '\'' +
                '}';
    }
}

class Movie {
    private String movieId;
    private String title;
    private String director;
    private List<String> actors;
    private String description;
    private int duration;
    private double rating;

    public Movie(String movieId, String title, String director, List<String> actors,
                 String description, int duration, double rating) {
        this.movieId = movieId;
        this.title = title;
        this.director = director;
        this.actors = actors;
        this.description = description;
        this.duration = duration;
        this.rating = rating;
    }

    public String getMovieId() { return movieId; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getDirector() { return director; }
    public void setDirector(String director) { this.director = director; }
    public List<String> getActors() { return actors; }
    public void setActors(List<String> actors) { this.actors = actors; }
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }
    public int getDuration() { return duration; }
    public void setDuration(int duration) { this.duration = duration; }
    public double getRating() { return rating; }
    public void setRating(double rating) { this.rating = rating; }

    @Override
    public String toString() {
        return "Movie{" +
                "movieId='" + movieId + '\'' +
                ", title='" + title + '\'' +
                ", director='" + director + '\'' +
                ", actors=" + actors +
                ", description='" + description + '\'' +
                ", duration=" + duration +
                ", rating=" + rating +
                '}';
    }
}

class ScreeningRoom {
    public enum RoomType { GOLD, SILVER, JADE, DIAMOND, GEM }

    private RoomType roomType;
    private int rows;
    private int seatsPerRow;

    public ScreeningRoom(RoomType roomType) {
        this.roomType = roomType;
        switch (roomType) {
            case GOLD: this.rows = 8; this.seatsPerRow = 10; break;
            case SILVER: this.rows = 10; this.seatsPerRow = 12; break;
            case JADE: case DIAMOND: this.rows = 7; this.seatsPerRow = 8; break;
            case GEM: this.rows = 8; this.seatsPerRow = 9; break;
        }
    }

    public RoomType getRoomType() { return roomType; }
    public int getRows() { return rows; }
    public int getSeatsPerRow() { return seatsPerRow; }
    public int getTotalSeats() { return rows * seatsPerRow; }

    @Override
    public String toString() {
        return "ScreeningRoom{" +
                "roomType=" + roomType +
                ", rows=" + rows +
                ", seatsPerRow=" + seatsPerRow +
                '}';
    }
}

class Screening {
    private String screeningId;
    private Movie movie;
    private ScreeningRoom room;
    private Date startTime;
    private Date endTime;
    private double price;
    private Seat[][] seats;

    public Screening(String screeningId, Movie movie, ScreeningRoom room,
                     Date startTime, double price) {
        this.screeningId = screeningId;
        this.movie = movie;
        this.room = room;
        this.startTime = startTime;
        this.price = price;
        long durationInMillis = movie.getDuration() * 60 * 1000L;
        this.endTime = new Date(startTime.getTime() + durationInMillis);
        initializeSeats();
    }

    private void initializeSeats() {
        int rows = room.getRows();
        int seatsPerRow = room.getSeatsPerRow();
        seats = new Seat[rows][seatsPerRow];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < seatsPerRow; j++) {
                seats[i][j] = new Seat(i + 1, j + 1);
            }
        }
    }

    public String getScreeningId() { return screeningId; }
    public Movie getMovie() { return movie; }
    public void setMovie(Movie movie) { this.movie = movie; }
    public ScreeningRoom getRoom() { return room; }
    public Date getStartTime() { return startTime; }
    public void setStartTime(Date startTime) { this.startTime = startTime; }
    public Date getEndTime() { return endTime; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
    public Seat[][] getSeats() { return seats; }

    public int getSoldSeatsCount() {
        int count = 0;
        for (Seat[] row : seats) {
            for (Seat seat : row) {
                if (seat.isOccupied()) count++;
            }
        }
        return count;
    }

    public int getAvailableSeatsCount() {
        return room.getTotalSeats() - getSoldSeatsCount();
    }

    public boolean hasTicketsSold() {
        return getSoldSeatsCount() > 0;
    }

    @Override
    public String toString() {
        return "Screening{" +
                "screeningId='" + screeningId + '\'' +
                ", movie=" + movie.getTitle() +
                ", room=" + room.getRoomType() +
                ", startTime=" + startTime +
                ", endTime=" + endTime +
                ", price=" + price +
                '}';
    }
}

class Seat {
    private int row;
    private int number;
    private boolean occupied;
    private String ticketId;

    public Seat(int row, int number) {
        this.row = row;
        this.number = number;
        this.occupied = false;
        this.ticketId = null;
    }

    public int getRow() { return row; }
    public int getNumber() { return number; }
    public boolean isOccupied() { return occupied; }
    public void setOccupied(boolean occupied) { this.occupied = occupied; }
    public String getTicketId() { return ticketId; }
    public void setTicketId(String ticketId) { this.ticketId = ticketId; }

    @Override
    public String toString() {
        return "Seat{" +
                "row=" + row +
                ", number=" + number +
                ", occupied=" + occupied +
                '}';
    }
}

class Ticket {
    private String ticketId;
    private Screening screening;
    private int row;
    private int seatNumber;
    private double price;
    private Date purchaseTime;
    private boolean isChildTicket;
    private boolean isRefunded;

    public Ticket(String ticketId, Screening screening, int row,
                  int seatNumber, double price, boolean isChildTicket) {
        this.ticketId = ticketId;
        this.screening = screening;
        this.row = row;
        this.seatNumber = seatNumber;
        this.price = price;
        this.purchaseTime = new Date();
        this.isChildTicket = isChildTicket;
        this.isRefunded = false;
    }

    public String getTicketId() { return ticketId; }
    public Screening getScreening() { return screening; }
    public int getRow() { return row; }
    public int getSeatNumber() { return seatNumber; }
    public double getPrice() { return price; }
    public Date getPurchaseTime() { return purchaseTime; }
    public boolean isChildTicket() { return isChildTicket; }
    public boolean isRefunded() { return isRefunded; }
    public void setRefunded(boolean refunded) { isRefunded = refunded; }

    @Override
    public String toString() {
        return "Ticket{" +
                "ticketId='" + ticketId + '\'' +
                ", movie=" + screening.getMovie().getTitle() +
                ", screeningTime=" + screening.getStartTime() +
                ", room=" + screening.getRoom().getRoomType() +
                ", row=" + row +
                ", seatNumber=" + seatNumber +
                ", price=" + price +
                ", isChildTicket=" + isChildTicket +
                '}';
    }
}

class SalesRecord {
    private String recordId;
    private Ticket ticket;
    private String operator;
    private Date operationTime;
    private OperationType operationType;

    public enum OperationType { PURCHASE, REFUND }

    public SalesRecord(String recordId, Ticket ticket, String operator,
                       OperationType operationType) {
        this.recordId = recordId;
        this.ticket = ticket;
        this.operator = operator;
        this.operationTime = new Date();
        this.operationType = operationType;
    }

    public String getRecordId() { return recordId; }
    public Ticket getTicket() { return ticket; }
    public String getOperator() { return operator; }
    public Date getOperationTime() { return operationTime; }
    public OperationType getOperationType() { return operationType; }

    @Override
    public String toString() {
        return "SalesRecord{" +
                "recordId='" + recordId + '\'' +
                ", ticket=" + ticket +
                ", operator='" + operator + '\'' +
                ", operationTime=" + operationTime +
                ", operationType=" + operationType +
                '}';
    }
}

class LogEntry {
    private String logId;
    private Date timestamp;
    private String operator;
    private String operationType;
    private String details;

    public LogEntry(String logId, String operator, String operationType, String details) {
        this.logId = logId;
        this.timestamp = new Date();
        this.operator = operator;
        this.operationType = operationType;
        this.details = details;
    }

    public String getLogId() { return logId; }
    public Date getTimestamp() { return timestamp; }
    public String getOperator() { return operator; }
    public String getOperationType() { return operationType; }
    public String getDetails() { return details; }

    @Override
    public String toString() {
        return "LogEntry{" +
                "logId='" + logId + '\'' +
                ", timestamp=" + timestamp +
                ", operator='" + operator + '\'' +
                ", operationType='" + operationType + '\'' +
                ", details='" + details + '\'' +
                '}';
    }
}

class DataStorage {
    private static Map<String, User> users = new HashMap<>();
    private static Map<String, Movie> movies = new HashMap<>();
    private static Map<ScreeningRoom.RoomType, ScreeningRoom> rooms = new HashMap<>();
    private static Map<String, Screening> screenings = new HashMap<>();
    private static Map<String, Ticket> tickets = new HashMap<>();
    private static List<SalesRecord> salesRecords = new ArrayList<>();
    private static List<LogEntry> logEntries = new ArrayList<>();

    public static void initialize() {
        User admin = new User("admin001", "admin", "ynuinfo#777", new Date(),
                User.UserType.ADMIN, "13800000000");
        users.put(admin.getUserId(), admin);

        for (ScreeningRoom.RoomType type : ScreeningRoom.RoomType.values()) {
            rooms.put(type, new ScreeningRoom(type));
        }
    }

    public static void addUser(User user) { users.put(user.getUserId(), user); }
    public static User getUserById(String userId) { return users.get(userId); }
    public static User getUserByUsername(String username) {
        for (User user : users.values()) {
            if (user.getUsername().equals(username)) return user;
        }
        return null;
    }
    public static List<User> getAllUsers() { return new ArrayList<>(users.values()); }
    public static void updateUser(User user) { users.put(user.getUserId(), user); }
    public static void deleteUser(String userId) { users.remove(userId); }

    public static void addMovie(Movie movie) { movies.put(movie.getMovieId(), movie); }
    public static Movie getMovieById(String movieId) { return movies.get(movieId); }
    public static List<Movie> getAllMovies() { return new ArrayList<>(movies.values()); }
    public static void updateMovie(Movie movie) { movies.put(movie.getMovieId(), movie); }
    public static void deleteMovie(String movieId) { movies.remove(movieId); }

    public static ScreeningRoom getRoomByType(ScreeningRoom.RoomType type) { return rooms.get(type); }
    public static List<ScreeningRoom> getAllRooms() { return new ArrayList<>(rooms.values()); }

    public static void addScreening(Screening screening) { screenings.put(screening.getScreeningId(), screening); }
    public static Screening getScreeningById(String screeningId) { return screenings.get(screeningId); }
    public static List<Screening> getAllScreenings() { return new ArrayList<>(screenings.values()); }
    public static void updateScreening(Screening screening) { screenings.put(screening.getScreeningId(), screening); }
    public static void deleteScreening(String screeningId) { screenings.remove(screeningId); }

    public static void addTicket(Ticket ticket) { tickets.put(ticket.getTicketId(), ticket); }
    public static Ticket getTicketById(String ticketId) { return tickets.get(ticketId); }
    public static List<Ticket> getAllTickets() { return new ArrayList<>(tickets.values()); }
    public static void updateTicket(Ticket ticket) { tickets.put(ticket.getTicketId(), ticket); }

    public static void addSalesRecord(SalesRecord record) { salesRecords.add(record); }
    public static List<SalesRecord> getAllSalesRecords() { return new ArrayList<>(salesRecords); }

    public static void addLogEntry(LogEntry logEntry) { logEntries.add(logEntry); }
    public static List<LogEntry> getAllLogEntries() { return new ArrayList<>(logEntries); }
}

class UserService {
    public static User authenticate(String username, String password) {
        User user = DataStorage.getUserByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            if (!user.isPasswordChanged() && !user.getUsername().equals("admin")) {
                System.out.println("首次登录，请修改默认密码！");
                return null;
            }
            return user;
        }
        return null;
    }

    public static User createUser(String username, User.UserType userType, String phone) {
        if (DataStorage.getUserByUsername(username) != null) {
            System.out.println("用户名已存在！");
            return null;
        }

        for (User user : DataStorage.getAllUsers()) {
            if (user.getPhone().equals(phone)) {
                System.out.println("手机号已被注册！");
                return null;
            }
        }

        String userId = UUID.randomUUID().toString();
        User user = new User(userId, username, "123456", new Date(), userType, phone);
        DataStorage.addUser(user);

        String logId = UUID.randomUUID().toString();
        String details = "新增用户: " + username + ", 类型: " + userType;
        DataStorage.addLogEntry(new LogEntry(logId, "system", "ADD_USER", details));
        return user;
    }

    public static boolean changePassword(User user, String newPassword) {
        user.setPassword(newPassword);
        user.setPasswordChanged(true);
        DataStorage.updateUser(user);

        String logId = UUID.randomUUID().toString();
        String details = "用户 " + user.getUsername() + " 修改了密码";
        DataStorage.addLogEntry(new LogEntry(logId, user.getUsername(), "CHANGE_PASSWORD", details));
        return true;
    }

    public static boolean resetPassword(User operator, User targetUser) {
        if (targetUser.getUsername().equals("admin")) {
            System.out.println("不能重置admin账户的密码！");
            return false;
        }

        targetUser.setPassword("123456");
        targetUser.setPasswordChanged(false);
        DataStorage.updateUser(targetUser);

        String logId = UUID.randomUUID().toString();
        String details = operator.getUsername() + " 重置了用户 " + targetUser.getUsername() + " 的密码";
        DataStorage.addLogEntry(new LogEntry(logId, operator.getUsername(), "RESET_PASSWORD", details));
        return true;
    }

    public static boolean deleteUser(User operator, String userId) {
        User user = DataStorage.getUserById(userId);
        if (user != null && user.getUsername().equals("admin")) {
            System.out.println("不能删除admin账户！");
            return false;
        }

        DataStorage.deleteUser(userId);

        String logId = UUID.randomUUID().toString();
        String details = operator.getUsername() + " 删除了用户 " + user.getUsername();
        DataStorage.addLogEntry(new LogEntry(logId, operator.getUsername(), "DELETE_USER", details));
        return true;
    }
}

class MovieService {
    public static Movie addMovie(String title, String director, List<String> actors,
                                 String description, int duration, double rating) {
        for (Movie movie : DataStorage.getAllMovies()) {
            if (movie.getTitle().equals(title)) {
                System.out.println("影片已存在！");
                return null;
            }
        }

        String movieId = UUID.randomUUID().toString();
        Movie movie = new Movie(movieId, title, director, actors, description, duration, rating);
        DataStorage.addMovie(movie);
        return movie;
    }

    public static boolean updateMovie(String movieId, String title, String director,
                                      List<String> actors, String description,
                                      int duration, double rating) {
        Movie movie = DataStorage.getMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return false;
        }

        movie.setTitle(title);
        movie.setDirector(director);
        movie.setActors(actors);
        movie.setDescription(description);
        movie.setDuration(duration);
        movie.setRating(rating);

        DataStorage.updateMovie(movie);
        return true;
    }

    public static boolean deleteMovie(String movieId) {
        for (Screening screening : DataStorage.getAllScreenings()) {
            if (screening.getMovie().getMovieId().equals(movieId)) {
                System.out.println("影片已有排片，不能删除！");
                return false;
            }
        }

        DataStorage.deleteMovie(movieId);
        return true;
    }

    public static List<Movie> searchMovies(String title, String director, String actor) {
        List<Movie> result = new ArrayList<>();

        for (Movie movie : DataStorage.getAllMovies()) {
            boolean match = true;

            if (title != null && !movie.getTitle().contains(title)) match = false;
            if (director != null && !movie.getDirector().contains(director)) match = false;

            if (actor != null) {
                boolean actorFound = false;
                for (String a : movie.getActors()) {//
                    if (a.contains(actor)) {
                        actorFound = true;
                        break;
                    }
                }
                if (!actorFound) match = false;
            }

            if (match) result.add(movie);
        }

        return result;
    }
}

class ScreeningService {
    public static Screening addScreening(String movieId, ScreeningRoom.RoomType roomType,
                                         Date startTime, double price) {
        Movie movie = DataStorage.getMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return null;
        }

        ScreeningRoom room = DataStorage.getRoomByType(roomType);
        if (room == null) {
            System.out.println("放映厅不存在！");
            return null;
        }

        for (Screening existing : DataStorage.getAllScreenings()) {
            if (existing.getRoom().getRoomType() == roomType) {
                if ((startTime.after(existing.getStartTime()) &&
                        startTime.before(existing.getEndTime())) ||
                        (startTime.getTime() + movie.getDuration() * 60 * 1000L >
                                existing.getStartTime().getTime() &&
                                startTime.getTime() + movie.getDuration() * 60 * 1000L <
                                        existing.getEndTime().getTime())) {
                    System.out.println("时间冲突！");
                    return null;
                }
            }
        }

        String screeningId = UUID.randomUUID().toString();
        Screening screening = new Screening(screeningId, movie, room, startTime, price);
        DataStorage.addScreening(screening);
        return screening;
    }

    public static boolean updateScreening(String screeningId, String newMovieId,
                                          Date newStartTime, double newPrice) {
        Screening screening = DataStorage.getScreeningById(screeningId);
        if (screening == null) {
            System.out.println("场次不存在！");
            return false;
        }

        if (screening.hasTicketsSold()) {
            System.out.println("该场次已有票售出，不能修改！");
            return false;
        }

        Movie newMovie = DataStorage.getMovieById(newMovieId);
        if (newMovie == null) {
            System.out.println("新影片不存在！");
            return false;
        }

        for (Screening existing : DataStorage.getAllScreenings()) {
            if (!existing.getScreeningId().equals(screeningId) &&
                    existing.getRoom().getRoomType() == screening.getRoom().getRoomType()) {
                if ((newStartTime.after(existing.getStartTime()) &&
                        newStartTime.before(existing.getEndTime())) ||
                        (newStartTime.getTime() + newMovie.getDuration() * 60 * 1000L >
                                existing.getStartTime().getTime() &&
                                newStartTime.getTime() + newMovie.getDuration() * 60 * 1000L <
                                        existing.getEndTime().getTime())) {
                    System.out.println("时间冲突！");
                    return false;
                }
            }
        }

        String originalMovie = screening.getMovie().getTitle();
        screening.setMovie(newMovie);
        screening.setStartTime(newStartTime);
        screening.setPrice(newPrice);
        DataStorage.updateScreening(screening);

        String logId = UUID.randomUUID().toString();
        String details = "修改场次: " + screeningId + ", 原影片: " + originalMovie +
                ", 新影片: " + newMovie.getTitle();
        DataStorage.addLogEntry(new LogEntry(logId, "system", "UPDATE_SCREENING", details));
        return true;
    }

    public static boolean deleteScreening(String screeningId) {
        Screening screening = DataStorage.getScreeningById(screeningId);
        if (screening == null) {
            System.out.println("场次不存在！");
            return false;
        }

        if (screening.hasTicketsSold()) {
            System.out.println("该场次已有票售出，不能删除！");
            return false;
        }

        String movieTitle = screening.getMovie().getTitle();
        DataStorage.deleteScreening(screeningId);

        String logId = UUID.randomUUID().toString();
        String details = "删除场次: " + screeningId + ", 影片: " + movieTitle;
        DataStorage.addLogEntry(new LogEntry(logId, "system", "DELETE_SCREENING", details));
        return true;
    }

    public static void autoScheduleMovies(List<String> movieIds) {
        List<ScreeningRoom> rooms = DataStorage.getAllRooms();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 10);

        for (String movieId : movieIds) {
            Movie movie = DataStorage.getMovieById(movieId);
            if (movie == null) continue;

            double price = 50.0;
            if (movie.getRating() >= 8.0) price = 80.0;

            for (ScreeningRoom room : rooms) {
                if (movie.getRating() < 7.0 && room.getRoomType() == ScreeningRoom.RoomType.GOLD) {
                    continue;
                }

                int screeningsPerDay = 2;
                if (movie.getRating() >= 8.0) screeningsPerDay = 4;

                for (int day = 0; day < 7; day++) {
                    for (int i = 0; i < screeningsPerDay; i++) {
                        calendar.set(Calendar.HOUR_OF_DAY, 10 + i * 4);

                        boolean isWeekend = calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
                                calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
                        boolean isEvening = calendar.get(Calendar.HOUR_OF_DAY) >= 18;

                        double screeningPrice = price;
                        if (isWeekend || isEvening) screeningPrice *= 1.2;

                        addScreening(movieId, room.getRoomType(), calendar.getTime(), screeningPrice);
                    }
                    calendar.add(Calendar.DATE, 1);
                    calendar.set(Calendar.HOUR_OF_DAY, 10);
                }
                calendar.add(Calendar.DATE, -7);
            }
        }
    }

    public static List<Screening> getScreeningsInRange(Date start, Date end) {
        List<Screening> result = new ArrayList<>();
        for (Screening screening : DataStorage.getAllScreenings()) {
            if (screening.getStartTime().after(start) &&
                    screening.getStartTime().before(end)) {
                result.add(screening);
            }
        }
        return result;
    }
}

class TicketService {
    public static Ticket sellTicket(String screeningId, int row, int seatNumber,
                                    boolean isChildTicket, String operator) {
        Screening screening = DataStorage.getScreeningById(screeningId);
        if (screening == null) {
            System.out.println("场次不存在！");
            return null;
        }

        if (row < 1 || row > screening.getRoom().getRows() ||
                seatNumber < 1 || seatNumber > screening.getRoom().getSeatsPerRow()) {
            System.out.println("无效的座位号！");
            return null;
        }

        Seat seat = screening.getSeats()[row-1][seatNumber-1];
        if (seat.isOccupied()) {
            System.out.println("该座位已被占用！");
            return null;
        }

        double price = screening.getPrice();
        if (isChildTicket) price *= 0.5;

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(screening.getStartTime());
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour >= 10 && hour < 12) price *= 0.9;

        String ticketId = UUID.randomUUID().toString();
        Ticket ticket = new Ticket(ticketId, screening, row, seatNumber, price, isChildTicket);
        seat.setOccupied(true);
        seat.setTicketId(ticketId);
        DataStorage.addTicket(ticket);

        String recordId = UUID.randomUUID().toString();
        DataStorage.addSalesRecord(new SalesRecord(recordId, ticket, operator,
                SalesRecord.OperationType.PURCHASE));
        return ticket;
    }

    public static boolean refundTicket(String ticketId, String operator) {
        Ticket ticket = DataStorage.getTicketById(ticketId);
        if (ticket == null) {
            System.out.println("票不存在！");
            return false;
        }

        if (ticket.isRefunded()) {
            System.out.println("该票已退过！");
            return false;
        }

        Date now = new Date();
        if (now.after(ticket.getScreening().getStartTime())) {
            System.out.println("电影已开始，不能退票！");
            return false;
        }

        double refundAmount = ticket.getPrice();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(ticket.getScreening().getStartTime());
        calendar.add(Calendar.DATE, -1);

        if (now.before(calendar.getTime())) {
            System.out.println("全额退款: " + refundAmount);
        } else {
            refundAmount *= 0.9;
            System.out.println("扣除10%手续费，退款: " + refundAmount);
        }

        ticket.setRefunded(true);
        DataStorage.updateTicket(ticket);

        Screening screening = ticket.getScreening();
        screening.getSeats()[ticket.getRow()-1][ticket.getSeatNumber()-1].setOccupied(false);
        screening.getSeats()[ticket.getRow()-1][ticket.getSeatNumber()-1].setTicketId(null);
        DataStorage.updateScreening(screening);

        String recordId = UUID.randomUUID().toString();
        DataStorage.addSalesRecord(new SalesRecord(recordId, ticket, operator,
                SalesRecord.OperationType.REFUND));
        return true;
    }

    public static SalesStatistics getSalesStatistics(Date start, Date end) {
        SalesStatistics stats = new SalesStatistics();
        for (SalesRecord record : DataStorage.getAllSalesRecords()) {
            if (record.getOperationTime().after(start) &&
                    record.getOperationTime().before(end)) {
                if (record.getOperationType() == SalesRecord.OperationType.PURCHASE) {
                    stats.totalTicketsSold++;
                    stats.totalRevenue += record.getTicket().getPrice();
                } else {
                    stats.totalTicketsRefunded++;
                    stats.totalRefundAmount += record.getTicket().getPrice() * 0.9;
                }
            }
        }
        return stats;
    }

    public static class SalesStatistics {
        public int totalTicketsSold;
        public int totalTicketsRefunded;
        public double totalRevenue;
        public double totalRefundAmount;

        @Override
        public String toString() {
            return "销售统计: " +
                    "售出票数=" + totalTicketsSold +
                    ", 退票数=" + totalTicketsRefunded +
                    ", 总收入=" + totalRevenue +
                    ", 总退款=" + totalRefundAmount;
        }
    }
}

class AdminMenu {
    public static void showMenu(User admin, Scanner scanner) {
        while (true) {
            System.out.println("\n=== 管理员菜单 ===");
            System.out.println("1. 密码管理");
            System.out.println("2. 用户管理");
            System.out.println("3. 退出登录");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    passwordManagement(admin, scanner);
                    break;
                case 2:
                    userManagement(admin, scanner);
                    break;
                case 3:
                    System.out.println("退出登录...");
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void passwordManagement(User admin, Scanner scanner) {
        System.out.println("\n=== 密码管理 ===");
        System.out.println("1. 修改自身密码");
        System.out.println("2. 重置其他用户密码");
        System.out.println("3. 返回");
        System.out.print("请选择: ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                changeOwnPassword(admin, scanner);
                break;//
            case 2:
                resetOtherUserPassword(admin, scanner);
                break;
            case 3:
                return;
            default:
                System.out.println("无效选择，请重新输入。");
        }
    }

    private static void changeOwnPassword(User admin, Scanner scanner) {
        System.out.print("请输入当前密码: ");
        String currentPassword = scanner.nextLine();

        if (!admin.getPassword().equals(currentPassword)) {
            System.out.println("当前密码错误！");
            return;
        }

        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();

        System.out.print("请再次输入新密码: ");
        String confirmPassword = scanner.nextLine();

        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的密码不一致！");
            return;
        }

        UserService.changePassword(admin, newPassword);
        System.out.println("密码修改成功！");
    }

    private static void resetOtherUserPassword(User admin, Scanner scanner) {
        System.out.print("请输入要重置密码的用户名: ");
        String username = scanner.nextLine();

        User targetUser = DataStorage.getUserByUsername(username);
        if (targetUser == null) {
            System.out.println("用户不存在！");
            return;
        }

        if (targetUser.getUserType() == User.UserType.ADMIN &&
                !targetUser.getUsername().equals(admin.getUsername())) {
            System.out.println("不能重置其他管理员的密码！");
            return;
        }

        UserService.resetPassword(admin, targetUser);
        System.out.println("密码已重置为123456，用户下次登录时需要修改密码。");
    }

    private static void userManagement(User admin, Scanner scanner) {
        while (true) {
            System.out.println("\n=== 用户管理 ===");
            System.out.println("1. 列出所有用户");
            System.out.println("2. 查询用户");
            System.out.println("3. 添加用户");
            System.out.println("4. 修改用户");
            System.out.println("5. 删除用户");
            System.out.println("6. 返回");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    listAllUsers();
                    break;
                case 2:
                    searchUser(scanner);//
                    break;
                case 3:
                    addUser(admin, scanner);
                    break;
                case 4:
                    updateUser(admin, scanner);
                    break;
                case 5:
                    deleteUser(admin, scanner);
                    break;//
                case 6:
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void listAllUsers() {
        List<User> users = DataStorage.getAllUsers();
        System.out.println("\n=== 所有用户 ===");
        for (User user : users) {
            System.out.println(user);
        }
    }

    private static void searchUser(Scanner scanner) {
        System.out.println("\n=== 查询用户 ===");
        System.out.println("1. 按用户ID查询");
        System.out.println("2. 按用户名查询");//
        System.out.println("3. 返回");
        System.out.print("请选择: ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                System.out.print("请输入用户ID: ");
                String userId = scanner.nextLine();
                User userById = DataStorage.getUserById(userId);
                if (userById != null) {
                    System.out.println(userById);
                } else {
                    System.out.println("用户不存在！");
                }
                break;
            case 2:
                System.out.print("请输入用户名: ");
                String username = scanner.nextLine();
                User userByName = DataStorage.getUserByUsername(username);
                if (userByName != null) {//
                    System.out.println(userByName);
                } else {
                    System.out.println("用户不存在！");
                }
                break;
            case 3:
                return;
            default:
                System.out.println("无效选择，请重新输入。");
        }
    }

    private static void addUser(User admin, Scanner scanner) {
        System.out.println("\n=== 添加用户 ===");
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();

        System.out.print("请输入用户类型 (1.管理员 2.经理 3.前台): ");
        int typeChoice = scanner.nextInt();
        scanner.nextLine();

        User.UserType userType;
        switch (typeChoice) {
            case 1: userType = User.UserType.ADMIN; break;
            case 2: userType = User.UserType.MANAGER; break;
            case 3: userType = User.UserType.FRONT_DESK; break;
            default:
                System.out.println("无效选择，默认为前台用户。");//111111
                userType = User.UserType.FRONT_DESK;
        }

        System.out.print("请输入手机号: ");
        String phone = scanner.nextLine();

        User newUser = UserService.createUser(username, userType, phone);
        if (newUser != null) {
            System.out.println("用户添加成功！");
        }
    }

    private static void updateUser(User admin, Scanner scanner) {
        System.out.println("\n=== 修改用户 ===");
        System.out.print("请输入要修改的用户名: ");
        String username = scanner.nextLine();

        User targetUser = DataStorage.getUserByUsername(username);
        if (targetUser == null) {
            System.out.println("用户不存在！");
            return;
        }

        if (targetUser.getUsername().equals("admin")) {
            System.out.println("不能修改admin账户的信息！");
            return;
        }

        System.out.println("当前用户信息: " + targetUser);
        System.out.print("修改用户类型 (1.经理 2.前台 3.不修改): ");
        int typeChoice = scanner.nextInt();
        scanner.nextLine();

        if (typeChoice == 1 || typeChoice == 2) {
            User.UserType newType = (typeChoice == 1) ? User.UserType.MANAGER : User.UserType.FRONT_DESK;
            targetUser.setUserType(newType);
        }

        System.out.print("请输入新手机号 (留空则不修改): ");
        String newPhone = scanner.nextLine();
        if (!newPhone.isEmpty()) {
            targetUser.setPhone(newPhone);
        }

        DataStorage.updateUser(targetUser);
        System.out.println("用户信息修改成功！");
    }

    private static void deleteUser(User admin, Scanner scanner) {
        System.out.println("\n=== 删除用户 ===");
        System.out.print("请输入要删除的用户名: ");
        String username = scanner.nextLine();

        User targetUser = DataStorage.getUserByUsername(username);
        if (targetUser == null) {
            System.out.println("用户不存在！");
            return;
        }

        System.out.println("警告：删除用户将永久删除该用户的所有信息！");
        System.out.print("确认删除用户 " + username + " 吗？(y/n): ");
        String confirm = scanner.nextLine();

        if (confirm.equalsIgnoreCase("y")) {
            boolean success = UserService.deleteUser(admin, targetUser.getUserId());
            if (success) {
                System.out.println("用户删除成功！");
            }
        } else {
            System.out.println("已取消删除操作。");
        }
    }
}

class ManagerMenu {
    public static void showMenu(User manager, Scanner scanner) {
        while (true) {
            System.out.println("\n=== 经理菜单 ===");
            System.out.println("1. 密码管理");
            System.out.println("2. 影片管理");
            System.out.println("3. 排片管理");
            System.out.println("4. 查看销售数据");
            System.out.println("5. 退出登录");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    passwordManagement(manager, scanner);
                    break;
                case 2:
                    movieManagement(manager, scanner);
                    break;
                case 3:
                    screeningManagement(manager, scanner);
                    break;
                case 4:
                    viewSalesData(manager, scanner);
                    break;
                case 5:
                    System.out.println("退出登录...");
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void passwordManagement(User manager, Scanner scanner) {
        System.out.println("\n=== 密码管理 ===");
        System.out.println("1. 修改自身密码");
        System.out.println("2. 重置前台密码");
        System.out.println("3. 返回");
        System.out.print("请选择: ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                changeOwnPassword(manager, scanner);
                break;
            case 2:
                resetFrontDeskPassword(manager, scanner);
                break;
            case 3:
                return;
            default:
                System.out.println("无效选择，请重新输入。");
        }
    }

    private static void changeOwnPassword(User manager, Scanner scanner) {
        System.out.print("请输入当前密码: ");
        String currentPassword = scanner.nextLine();

        if (!manager.getPassword().equals(currentPassword)) {
            System.out.println("当前密码错误！");
            return;
        }

        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();

        System.out.print("请再次输入新密码: ");
        String confirmPassword = scanner.nextLine();

        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的密码不一致！");
            return;
        }

        UserService.changePassword(manager, newPassword);
        System.out.println("密码修改成功！");
    }

    private static void resetFrontDeskPassword(User manager, Scanner scanner) {
        System.out.print("请输入要重置密码的前台用户名: ");
        String username = scanner.nextLine();

        User targetUser = DataStorage.getUserByUsername(username);
        if (targetUser == null) {
            System.out.println("用户不存在！");
            return;
        }

        if (targetUser.getUserType() != User.UserType.FRONT_DESK) {
            System.out.println("只能重置前台用户的密码！");
            return;
        }

        UserService.resetPassword(manager, targetUser);
        System.out.println("密码已重置为123456，用户下次登录时需要修改密码。");
    }

    private static void movieManagement(User manager, Scanner scanner) {
        while (true) {
            System.out.println("\n=== 影片管理 ===");
            System.out.println("1. 列出所有影片");
            System.out.println("2. 添加影片");
            System.out.println("3. 修改影片");
            System.out.println("4. 删除影片");
            System.out.println("5. 查询影片");
            System.out.println("6. 返回");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    listAllMovies();
                    break;
                case 2:
                    addMovie(manager, scanner);
                    break;
                case 3:
                    updateMovie(manager, scanner);
                    break;
                case 4:
                    deleteMovie(manager, scanner);
                    break;
                case 5:
                    searchMovie(scanner);
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void listAllMovies() {
        List<Movie> movies = DataStorage.getAllMovies();
        System.out.println("\n=== 所有影片 ===");
        for (Movie movie : movies) {
            System.out.println(movie);
        }
    }

    private static void addMovie(User manager, Scanner scanner) {
        System.out.println("\n=== 添加影片 ===");
        System.out.print("请输入片名: ");
        String title = scanner.nextLine();

        System.out.print("请输入导演: ");
        String director = scanner.nextLine();

        System.out.print("请输入主演 (多个主演用逗号分隔): ");
        String actorsInput = scanner.nextLine();
        List<String> actors = new ArrayList<>();
        for (String actor : actorsInput.split(",")) {
            actors.add(actor.trim());
        }

        System.out.print("请输入剧情简介: ");
        String description = scanner.nextLine();

        System.out.print("请输入时长 (分钟): ");
        int duration = scanner.nextInt();
        scanner.nextLine();

        System.out.print("请输入评分 (0-10): ");
        double rating = scanner.nextDouble();
        scanner.nextLine();

        Movie movie = MovieService.addMovie(title, director, actors, description, duration, rating);
        if (movie != null) {
            System.out.println("影片添加成功！");
        }
    }

    private static void updateMovie(User manager, Scanner scanner) {
        System.out.println("\n=== 修改影片 ===");
        System.out.print("请输入要修改的影片ID: ");
        String movieId = scanner.nextLine();

        Movie movie = DataStorage.getMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.println("当前影片信息: " + movie);
        System.out.print("请输入新片名 (留空则不修改): ");
        String title = scanner.nextLine();
        if (!title.isEmpty()) movie.setTitle(title);

        System.out.print("请输入新导演 (留空则不修改): ");
        String director = scanner.nextLine();
        if (!director.isEmpty()) movie.setDirector(director);

        System.out.print("请输入新主演 (多个主演用逗号分隔，留空则不修改): ");
        String actorsInput = scanner.nextLine();
        if (!actorsInput.isEmpty()) {
            List<String> actors = new ArrayList<>();
            for (String actor : actorsInput.split(",")) {
                actors.add(actor.trim());
            }
            movie.setActors(actors);
        }

        System.out.print("请输入新剧情简介 (留空则不修改): ");
        String description = scanner.nextLine();
        if (!description.isEmpty()) movie.setDescription(description);

        System.out.print("请输入新时长 (分钟，输入0则不修改): ");
        int duration = scanner.nextInt();
        scanner.nextLine();
        if (duration > 0) movie.setDuration(duration);

        System.out.print("请输入新评分 (0-10，输入-1则不修改): ");
        double rating = scanner.nextDouble();
        scanner.nextLine();
        if (rating >= 0) movie.setRating(rating);

        DataStorage.updateMovie(movie);
        System.out.println("影片信息修改成功！");
    }

    private static void deleteMovie(User manager, Scanner scanner) {
        System.out.println("\n=== 删除影片 ===");
        System.out.print("请输入要删除的影片ID: ");
        String movieId = scanner.nextLine();

        Movie movie = DataStorage.getMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.println("警告：删除影片将永久删除该影片的所有信息！");
        System.out.print("确认删除影片 " + movie.getTitle() + " 吗？(y/n): ");
        String confirm = scanner.nextLine();

        if (confirm.equalsIgnoreCase("y")) {
            boolean success = MovieService.deleteMovie(movieId);
            if (success) {
                System.out.println("影片删除成功！");
            }
        } else {
            System.out.println("已取消删除操作。");
        }
    }

    private static void searchMovie(Scanner scanner) {
        System.out.println("\n=== 查询影片 ===");
        System.out.print("请输入片名 (留空则不限制): ");
        String title = scanner.nextLine();

        System.out.print("请输入导演 (留空则不限制): ");
        String director = scanner.nextLine();

        System.out.print("请输入主演 (留空则不限制): ");
        String actor = scanner.nextLine();

        List<Movie> results = MovieService.searchMovies(
                title.isEmpty() ? null : title,
                director.isEmpty() ? null : director,
                actor.isEmpty() ? null : actor
        );

        System.out.println("\n=== 查询结果 ===");
        for (Movie movie : results) {
            System.out.println(movie);
        }
    }

    private static void screeningManagement(User manager, Scanner scanner) {
        while (true) {
            System.out.println("\n=== 排片管理 ===");
            System.out.println("1. 增加场次");
            System.out.println("2. 修改场次");
            System.out.println("3. 删除场次");
            System.out.println("4. 列出所有场次");
            System.out.println("5. 自动排片");
            System.out.println("6. 返回");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    addScreening(manager, scanner);
                    break;
                case 2:
                    updateScreening(manager, scanner);
                    break;
                case 3:
                    deleteScreening(manager, scanner);
                    break;
                case 4:
                    listScreenings(scanner);
                    break;
                case 5:
                    autoSchedule(manager, scanner);
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void addScreening(User manager, Scanner scanner) {
        System.out.println("\n=== 增加场次 ===");
        List<Movie> movies = DataStorage.getAllMovies();
        System.out.println("=== 所有影片 ===");
        for (int i = 0; i < movies.size(); i++) {
            System.out.println((i+1) + ". " + movies.get(i).getTitle());
        }

        System.out.print("请选择影片编号: ");
        int movieIndex = scanner.nextInt() - 1;
        scanner.nextLine();

        if (movieIndex < 0 || movieIndex >= movies.size()) {
            System.out.println("无效的影片编号！");
            return;
        }

        Movie movie = movies.get(movieIndex);
        List<ScreeningRoom> rooms = DataStorage.getAllRooms();
        System.out.println("=== 所有放映厅 ===");
        for (int i = 0; i < rooms.size(); i++) {
            System.out.println((i+1) + ". " + rooms.get(i).getRoomType());
        }

        System.out.print("请选择放映厅编号: ");
        int roomIndex = scanner.nextInt() - 1;
        scanner.nextLine();

        if (roomIndex < 0 || roomIndex >= rooms.size()) {
            System.out.println("无效的放映厅编号！");
            return;
        }

        ScreeningRoom room = rooms.get(roomIndex);
        System.out.print("请输入开始时间 (格式: yyyy-MM-dd HH:mm): ");
        String timeInput = scanner.nextLine();
        Date startTime = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            startTime = sdf.parse(timeInput);
        } catch (Exception e) {
            System.out.println("时间格式错误！");
            return;
        }

        System.out.print("请输入票价: ");
        double price = scanner.nextDouble();
        scanner.nextLine();

        Screening screening = ScreeningService.addScreening(movie.getMovieId(), room.getRoomType(), startTime, price);
        if (screening != null) {
            System.out.println("场次添加成功！");
        }
    }

    private static void updateScreening(User manager, Scanner scanner) {
        System.out.println("\n=== 修改场次 ===");
        List<Screening> screenings = DataStorage.getAllScreenings();
        System.out.println("=== 所有场次 ===");
        for (int i = 0; i < screenings.size(); i++) {
            System.out.println((i+1) + ". " + screenings.get(i));
        }

        System.out.print("请选择场次编号: ");
        int screeningIndex = scanner.nextInt() - 1;
        scanner.nextLine();

        if (screeningIndex < 0 || screeningIndex >= screenings.size()) {
            System.out.println("无效的场次编号！");
            return;
        }

        Screening screening = screenings.get(screeningIndex);
        List<Movie> movies = DataStorage.getAllMovies();
        System.out.println("=== 所有影片 ===");
        for (int i = 0; i < movies.size(); i++) {
            System.out.println((i+1) + ". " + movies.get(i).getTitle());
        }

        System.out.print("请选择新影片编号 (输入0保持原影片): ");
        int movieIndex = scanner.nextInt() - 1;
        scanner.nextLine();

        String newMovieId = screening.getMovie().getMovieId();
        if (movieIndex >= 0 && movieIndex < movies.size()) {
            newMovieId = movies.get(movieIndex).getMovieId();
        }

        System.out.print("请输入新开始时间 (格式: yyyy-MM-dd HH:mm，留空则保持原时间): ");
        String timeInput = scanner.nextLine();
        Date newStartTime = screening.getStartTime();
        if (!timeInput.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                newStartTime = sdf.parse(timeInput);
            } catch (Exception e) {
                System.out.println("时间格式错误！");
                return;
            }
        }

        System.out.print("请输入新票价 (输入0保持原价): ");
        double newPrice = scanner.nextDouble();
        scanner.nextLine();
        if (newPrice <= 0) newPrice = screening.getPrice();

        boolean success = ScreeningService.updateScreening(
                screening.getScreeningId(),
                newMovieId,
                newStartTime,
                newPrice
        );

        if (success) System.out.println("场次修改成功！");
    }

    private static void deleteScreening(User manager, Scanner scanner) {
        System.out.println("\n=== 删除场次 ===");
        List<Screening> screenings = DataStorage.getAllScreenings();
        System.out.println("=== 所有场次 ===");
        for (int i = 0; i < screenings.size(); i++) {
            System.out.println((i+1) + ". " + screenings.get(i));
        }

        System.out.print("请选择场次编号: ");
        int screeningIndex = scanner.nextInt() - 1;
        scanner.nextLine();

        if (screeningIndex < 0 || screeningIndex >= screenings.size()) {
            System.out.println("无效的场次编号！");
            return;
        }

        Screening screening = screenings.get(screeningIndex);
        System.out.println("警告：删除场次将永久删除该场次的所有信息！");
        System.out.print("确认删除场次 " + screening + " 吗？(y/n): ");
        String confirm = scanner.nextLine();

        if (confirm.equalsIgnoreCase("y")) {
            boolean success = ScreeningService.deleteScreening(screening.getScreeningId());
            if (success) System.out.println("场次删除成功！");
        } else {
            System.out.println("已取消删除操作。");
        }
    }

    private static void listScreenings(Scanner scanner) {
        System.out.println("\n=== 列出场次 ===");
        System.out.println("1. 列出当日场次");
        System.out.println("2. 列出近3日场次");
        System.out.println("3. 列出近一周场次");
        System.out.println("4. 返回");
        System.out.print("请选择: ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        Date startDate = now;
        Date endDate = now;

        switch (choice) {
            case 1:
                calendar.add(Calendar.DATE, 1);
                endDate = calendar.getTime();
                break;
            case 2:
                calendar.add(Calendar.DATE, 3);
                endDate = calendar.getTime();
                break;
            case 3:
                calendar.add(Calendar.DATE, 7);
                endDate = calendar.getTime();
                break;
            case 4:
                return;
            default:
                System.out.println("无效选择，请重新输入。");
                return;
        }

        List<Screening> screenings = ScreeningService.getScreeningsInRange(startDate, endDate);
        System.out.println("\n=== 场次列表 ===");
        for (Screening screening : screenings) {
            System.out.println(screening);
        }
    }

    private static void autoSchedule(User manager, Scanner scanner) {
        System.out.println("\n=== 自动排片 ===");
        List<Movie> movies = DataStorage.getAllMovies();
        System.out.println("=== 所有影片 ===");
        for (int i = 0; i < movies.size(); i++) {
            System.out.println((i+1) + ". " + movies.get(i).getTitle());
        }

        System.out.print("请选择要排片的影片编号 (多个用逗号分隔，输入0选择全部): ");
        String selection = scanner.nextLine();

        List<String> movieIds = new ArrayList<>();
        if (selection.equals("0")) {
            for (Movie movie : movies) {
                movieIds.add(movie.getMovieId());
            }
        } else {
            for (String num : selection.split(",")) {
                try {
                    int index = Integer.parseInt(num.trim()) - 1;
                    if (index >= 0 && index < movies.size()) {
                        movieIds.add(movies.get(index).getMovieId());
                    }
                } catch (NumberFormatException e) {}
            }
        }

        if (movieIds.isEmpty()) {
            System.out.println("没有选择任何影片！");
            return;
        }

        ScreeningService.autoScheduleMovies(movieIds);
        System.out.println("自动排片完成！");
    }

    private static void viewSalesData(User manager, Scanner scanner) {
        System.out.println("\n=== 查看销售数据 ===");
        System.out.println("1. 查看当日销售数据");
        System.out.println("2. 查看当周销售数据");
        System.out.println("3. 查看当月销售数据");
        System.out.println("4. 返回");
        System.out.print("请选择: ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        Date startDate = now;
        Date endDate = now;

        switch (choice) {
            case 1:
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                startDate = calendar.getTime();
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                endDate = calendar.getTime();
                break;
            case 2:
                calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                startDate = calendar.getTime();
                calendar.add(Calendar.DATE, 6);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                endDate = calendar.getTime();
                break;
            case 3:
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                startDate = calendar.getTime();
                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                endDate = calendar.getTime();
                break;
            case 4:
                return;
            default:
                System.out.println("无效选择，请重新输入。");
                return;
        }

        TicketService.SalesStatistics stats = TicketService.getSalesStatistics(startDate, endDate);
        System.out.println("\n=== 销售统计 ===");
        System.out.println(stats);
    }
}

class FrontDeskMenu {
    public static void showMenu(User frontDesk, Scanner scanner) {
        while (true) {
            System.out.println("\n=== 前台菜单 ===");
            System.out.println("1. 列出所有影片");
            System.out.println("2. 列出所有场次");
            System.out.println("3. 查看场次座位");
            System.out.println("4. 售票");
            System.out.println("5. 退票");
            System.out.println("6. 修改密码");
            System.out.println("7. 退出登录");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    listAllMovies();
                    break;
                case 2:
                    listScreenings(scanner);
                    break;
                case 3:
                    viewSeating(scanner);
                    break;
                case 4:
                    sellTicket(frontDesk, scanner);
                    break;
                case 5:
                    refundTicket(frontDesk, scanner);
                    break;
                case 6:
                    changePassword(frontDesk, scanner);
                    break;
                case 7:
                    System.out.println("退出登录...");
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void listAllMovies() {
        List<Movie> movies = DataStorage.getAllMovies();
        System.out.println("\n=== 所有影片 ===");
        for (Movie movie : movies) {
            System.out.println(movie);
        }
    }

    private static void listScreenings(Scanner scanner) {
        System.out.println("\n=== 列出场次 ===");
        System.out.println("1. 列出当日场次");
        System.out.println("2. 列出近3日场次");
        System.out.println("3. 列出近一周场次");
        System.out.println("4. 返回");
        System.out.print("请选择: ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        Date startDate = now;
        Date endDate = now;

        switch (choice) {
            case 1:
                calendar.add(Calendar.DATE, 1);
                endDate = calendar.getTime();
                break;
            case 2:
                calendar.add(Calendar.DATE, 3);
                endDate = calendar.getTime();
                break;
            case 3:
                calendar.add(Calendar.DATE, 7);
                endDate = calendar.getTime();
                break;
            case 4:
                return;
            default:
                System.out.println("无效选择，请重新输入。");
                return;
        }

        List<Screening> screenings = ScreeningService.getScreeningsInRange(startDate, endDate);
        System.out.println("\n=== 场次列表 ===");
        for (Screening screening : screenings) {
            System.out.println(screening);
        }
    }

    private static void viewSeating(Scanner scanner) {
        System.out.println("\n=== 查看场次座位 ===");
        List<Screening> screenings = DataStorage.getAllScreenings();
        System.out.println("=== 所有场次 ===");
        for (int i = 0; i < screenings.size(); i++) {
            System.out.println((i+1) + ". " + screenings.get(i));
        }

        System.out.print("请选择场次编号: ");
        int screeningIndex = scanner.nextInt() - 1;
        scanner.nextLine();

        if (screeningIndex < 0 || screeningIndex >= screenings.size()) {
            System.out.println("无效的场次编号！");
            return;
        }

        Screening screening = screenings.get(screeningIndex);
        Seat[][] seats = screening.getSeats();

        System.out.println("\n=== 座位图 ===");
        System.out.println("X: 已售  O: 可用");
        System.out.print("   ");
        for (int i = 1; i <= seats[0].length; i++) {
            System.out.printf("%2d ", i);
        }
        System.out.println();

        for (int i = 0; i < seats.length; i++) {
            System.out.printf("%2d ", i+1);
            for (int j = 0; j < seats[i].length; j++) {
                System.out.print(seats[i][j].isOccupied() ? " X " : " O ");
            }
            System.out.println();
        }

        System.out.println("总座位数: " + screening.getRoom().getTotalSeats());
        System.out.println("可用座位数: " + screening.getAvailableSeatsCount());
    }

    private static void sellTicket(User frontDesk, Scanner scanner) {
        System.out.println("\n=== 售票 ===");
        List<Screening> screenings = DataStorage.getAllScreenings();
        System.out.println("=== 所有场次 ===");
        for (int i = 0; i < screenings.size(); i++) {
            System.out.println((i+1) + ". " + screenings.get(i));
        }

        System.out.print("请选择场次编号: ");
        int screeningIndex = scanner.nextInt() - 1;
        scanner.nextLine();

        if (screeningIndex < 0 || screeningIndex >= screenings.size()) {
            System.out.println("无效的场次编号！");
            return;
        }

        Screening screening = screenings.get(screeningIndex);
        Seat[][] seats = screening.getSeats();
        System.out.println("\n=== 座位图 ===");
        System.out.print("   ");
        for (int i = 1; i <= seats[0].length; i++) {
            System.out.printf("%2d ", i);
        }
        System.out.println();

        for (int i = 0; i < seats.length; i++) {
            System.out.printf("%2d ", i+1);
            for (int j = 0; j < seats[i].length; j++) {
                System.out.print(seats[i][j].isOccupied() ? " X " : " O ");
            }
            System.out.println();
        }

        System.out.print("请输入要购买的票数: ");
        int ticketCount = scanner.nextInt();
        scanner.nextLine();

        if (ticketCount <= 0 || ticketCount > screening.getAvailableSeatsCount()) {
            System.out.println("无效的票数！");
            return;
        }

        List<Ticket> tickets = new ArrayList<>();

        for (int i = 0; i < ticketCount; i++) {
            System.out.print("请输入第" + (i+1) + "张票的行号: ");
            int row = scanner.nextInt();

            System.out.print("请输入第" + (i+1) + "张票的座位号: ");
            int seatNumber = scanner.nextInt();

            System.out.print("是否是儿童票? (y/n): ");
            String isChildInput = scanner.nextLine();
            boolean isChild = isChildInput.equalsIgnoreCase("y");

            Ticket ticket = TicketService.sellTicket(
                    screening.getScreeningId(),
                    row,
                    seatNumber,
                    isChild,
                    frontDesk.getUsername()
            );

            if (ticket != null) {
                tickets.add(ticket);
                System.out.println("票购买成功！票号: " + ticket.getTicketId());
            } else {
                System.out.println("购票失败！");
                return;
            }
        }

        System.out.println("\n=== 票信息 ===");
        for (Ticket ticket : tickets) {
            System.out.println(ticket);
        }
    }

    private static void refundTicket(User frontDesk, Scanner scanner) {
        System.out.println("\n=== 退票 ===");
        System.out.print("请输入要退的票号: ");
        String ticketId = scanner.nextLine();

        boolean success = TicketService.refundTicket(ticketId, frontDesk.getUsername());
        if (success) {
            System.out.println("退票成功！");
        } else {
            System.out.println("退票失败！");
        }
    }

    private static void changePassword(User frontDesk, Scanner scanner) {
        System.out.print("请输入当前密码: ");
        String currentPassword = scanner.nextLine();

        if (!frontDesk.getPassword().equals(currentPassword)) {
            System.out.println("当前密码错误！");
            return;
        }

        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();

        System.out.print("请再次输入新密码: ");
        String confirmPassword = scanner.nextLine();

        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的密码不一致！");
            return;
        }

        UserService.changePassword(frontDesk, newPassword);
        System.out.println("密码修改成功！");
    }
}

class SystemInitializer {
    public static void initialize() {
        if (DataStorage.getUserByUsername("admin") == null) {
            User admin = new User("admin001", "admin", "ynuinfo#777", new Date(),
                    User.UserType.ADMIN, "13800000000");
            admin.setPasswordChanged(true);
            DataStorage.addUser(admin);
        }

        if (DataStorage.getUserByUsername("manager") == null) {
            User manager = new User("manager001", "manager", "123456", new Date(),
                    User.UserType.MANAGER, "13800000001");
            manager.setPasswordChanged(true);
            DataStorage.addUser(manager);
        }

        if (DataStorage.getUserByUsername("frontdesk") == null) {
            User frontDesk = new User("frontdesk001", "frontdesk", "123456", new Date(),
                    User.UserType.FRONT_DESK, "13800000002");
            frontDesk.setPasswordChanged(true);
            DataStorage.addUser(frontDesk);
        }

        if (DataStorage.getAllMovies().isEmpty()) {
            Movie movie1 = new Movie("movie001", "流浪地球", "郭帆",
                    Arrays.asList("吴京", "屈楚萧", "李光洁"),
                    "太阳即将毁灭，人类在地球表面建造出巨大的推进器，寻找新家园。",
                    125, 8.5);
            DataStorage.addMovie(movie1);

            Movie movie2 = new Movie("movie002", "哪吒之魔童降世", "饺子",
                    Arrays.asList("吕艳婷", "囧森瑟夫", "瀚墨"),
                    "天地灵气孕育出一颗能量巨大的混元珠，元始天尊将混元珠提炼成灵珠和魔丸...",
                    110, 9.0);
            DataStorage.addMovie(movie2);
        }
    }
}